# coding=utf-8


"""This is a basic module of python palo api wrapper"""

#33
#from urllib.parse import urlencode
#27
from urllib import urlencode
from urllib3 import PoolManager
from pypalo.tools import normalize

PM=PoolManager()

#default dictionary
default={}
default["host"]='localhost'
default["port"]=7921
default["user"]='admin'
default["password"]='admin'
default["sid"]=None 
default["timeinit"]=None
default["timeleft"]=None
default["database"]=None
default["dimension"]=None
default["element"]=None
default["cube"]=None
default["cell"]=None
default["path"]=None
default["rule"]=None
#All functions, that wrap api requests, must use value of this variable as the name of keyword arguments in their definition
default["kwargs_name"]="keywords"

def arguments(arg_dict):
	for arg in arg_dict:
		if arg==default["kwargs_name"]:
			for item in arg_dict[arg]:
				arg_dict[item]=arg_dict[arg][item]
			del arg_dict[arg]
			break
	del arg_dict['host']
	del arg_dict['port']
	return arg_dict

def address(host, port):
	'''This function returns address url.
	USAGE:
	address(host,port) returns string: 'http://host:port' '''
	#beginning of function suite
	#end of function suite
	return 'http://'+str(host)+':'+str(port)

def request(group, name):
	'''This function returns request url.
	USAGE:
	request(group, name) returns string: '/group/name' '''
	#beginning of function suite
	#end of function suite
	return '/'+str(group).lower()+'/'+str(name).lower()

def parameters(dictionary):
	'''This function converts parametrs dictionary to a "percent-encoded" string.
	USAGE:
	parametrs(dictionary) returns "percent-encoded" string'''
	#end of function suite
	return '?'+urlencode(dictionary)

def url(host, port, group, name, params):
	'''This function returns request url.
	USAGE:
	url(host, port, group, name, {parametrs}) returns request url'''
	return address(host,port)+request(group, name)+parameters(params)

def response(url):
	'''This function sends url request to palo server and converts the response string to some python object.
	USAGE:
	response(url) returns response as python object'''
	#beginning of function suite
	result=[]
	resp = PM.request('GET', url).data.decode('utf-8').splitlines()
	for line in resp:
		line=line[:-1].split(';')
		items=[]
		for item in line:
			items+=[normalize(item)]
		result+=[items]
	#end of function suite
	return result

# end of basic module suite